package ray.mgocc;

import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StoredSource implements Source{
    private final static Log log = LogFactory.getLog(StoredSource.class);

    private InputStream source = null;
    private File file = null;
    public StoredSource(InputStream source){
        this.source = source;
    }
    public StoredSource(File file){
        this.file = file;
    }
    public void finalize(){
        close();
    }
    public void close(){
        try{
            if(null!=source){
                source.close();
                source = null;
            }
        }catch(IOException e){
            log.error("can not close source.",e);
        }
    }
    public InputStream getStream(){
        InputStream in = this.source;
        if(null==in){
            File file = this.file;
            if(file.exists()){
                try{
                    in = new FileInputStream(this.file);
                }catch(FileNotFoundException e){
                    throw new RuntimeException("file removed.");
                }
            }
        }
        return in;
    }
}
